package com.study.web;

import com.study.bean.UserInfoTo;
import com.study.interceptor.CarInterceptor;
import com.study.service.CarService;
import com.study.utils.SysUtils;
import com.study.vo.Car;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;


@Controller
@RequestMapping("/car")
public class CarController {

    private static final Logger log = LoggerFactory.getLogger(CarController.class);

    /**
     * catList
     * 浏览器中保存cookie保存用户信息。
     * <p>
     * 没有登录，按照cookie的user-key来做，
     * 第一次：如果没有临时用户，帮忙创建也给临时用户
     *
     * @param session
     * @return
     */
    @GetMapping("catList.html")
    public String carList(HttpSession session) {

        ThreadLocal<UserInfoTo> localUser = CarInterceptor.localUser;

        System.out.println(localUser);

        Object attribute = session.getAttribute(SysUtils.LOGIN_NAME);
        if (attribute == null) {
            //    没有登录获取 临时购物车
        } else {
            //    获取登录了的购物车
        }
        return "";
    }

    @GetMapping("cat.html")
    public String carListPage(Model model) {

        Car car = carService.getCar();
        model.addAttribute("cart", car);

        return "catList";
    }

    @Autowired
    CarService carService;

    /**
     * 为了避免重复提交，添加成功重定向
     * <p>
     * RedirectAttributes： addFlashAttribute 数据放入session中，只能取一次；
     * <span></span>addAttribute:数据放入 url中。
     */
    @GetMapping("/addToCar")
    public String addToCar(@RequestParam(value = "skuId", required = false) Long skuid,
                           @RequestParam(value = "num", required = false) Integer num,
                           RedirectAttributes ra) {
        //CartItem cartItem = carService.addToCar(skuid, num);
        ra.addAttribute("skuId", skuid);
        return "redirect:/car/addToCatSuccess.html";
    }

    /**
     * 添加购物车重定向|http://localhost:9590/thy/car/addToCar?skuId=1&num=2
     */
    @GetMapping("addToCatSuccess.html")
    public String addToCatSuccess(@RequestParam(value = "skuId", required = false) Long skuid,
                                  Model model) {
        //carService.getCartItem(skuid);
        log.info("添加购物车重定向页面");
        //TODO 重定向到成功页面，再次查询购物车数量
        model.addAttribute("item", skuid + "购物车");
        model.addAttribute("time", SysUtils.getDateSpan());
        return "car/success";
    }

}
